/**
 * 百度智能云千帆API调用工具类
 * @author 
 */

const cloudBase = require('./cloud_base.js');
const cloudUtil = require('../utils/cloud_util.js');
const timeUtil = require('../utils/time_util.js');
const config = require('../../config/config.js');
const axios = require('axios');

class BaiduCloud {
    // 获取接口调用凭证
    static async getAccessToken() {
        // 尝试从数据库中获取缓存的token
        const tokenCollection = cloudBase.getCollection('access_tokens');
        const tokenRecord = await tokenCollection.where({
            TOKEN_TYPE: 'baidu_qianfan'
        }).limit(1).get();

        // 如果存在有效的token，直接返回
        if (tokenRecord && tokenRecord.data.length > 0) {
            const token = tokenRecord.data[0];
            const now = timeUtil.time();
            
            // 如果token未过期且剩余有效期大于10分钟，直接返回
            if (token.TOKEN_EXPIRE > now + 600) {
                return token.TOKEN_CONTENT;
            }
        }

        // 否则，请求新token
        try {
            const response = await axios({
                method: 'post',
                url: 'https://aip.baidubce.com/oauth/2.0/token',
                params: {
                    grant_type: 'client_credentials',
                    client_id: config.BAIDU_API_KEY, // 百度智能云应用的API Key
                    client_secret: config.BAIDU_SECRET_KEY // 百度智能云应用的Secret Key
                },
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            });

            if (response.status === 200 && response.data && response.data.access_token) {
                const accessToken = response.data.access_token;
                const expiresIn = response.data.expires_in || 2592000; // 默认30天有效期
                
                // 保存到数据库
                const now = timeUtil.time();
                const tokenData = {
                    TOKEN_TYPE: 'baidu_qianfan',
                    TOKEN_CONTENT: accessToken,
                    TOKEN_EXPIRE: now + expiresIn,
                    TOKEN_CREATE_TIME: now,
                    TOKEN_UPDATE_TIME: now
                };
                
                // 先删除旧记录
                await tokenCollection.where({
                    TOKEN_TYPE: 'baidu_qianfan'
                }).remove();
                
                // 再插入新记录
                await tokenCollection.add({
                    data: tokenData
                });
                
                return accessToken;
            } else {
                console.error('获取百度千帆access_token失败:', response.data);
                throw new Error('获取access_token失败');
            }
        } catch (error) {
            console.error('请求百度千帆access_token异常:', error);
            throw error;
        }
    }

    // 调用文心一言模型生成回答
    static async chatCompletion(messages, options = {}) {
        try {
            const accessToken = await this.getAccessToken();
            const modelName = options.model || 'ERNIE-Bot-4'; // 文心一言4.0模型
            const temperature = options.temperature || 0.7;
            const topP = options.top_p || 0.9;

            const response = await axios({
                method: 'post',
                url: `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/${modelName}?access_token=${accessToken}`,
                data: {
                    messages: messages,
                    temperature: temperature,
                    top_p: topP
                },
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (response.status === 200 && response.data) {
                return response.data;
            } else {
                console.error('调用百度千帆模型失败:', response.data);
                throw new Error('调用模型失败');
            }
        } catch (error) {
            console.error('请求百度千帆API异常:', error);
            throw error;
        }
    }

    // 获取文本的向量表示
    static async getEmbedding(text) {
        try {
            const accessToken = await this.getAccessToken();
            const modelName = 'Embedding-V1'; // 使用百度的Embedding模型

            const response = await axios({
                method: 'post',
                url: `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/embeddings/${modelName}?access_token=${accessToken}`,
                data: {
                    input: text
                },
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (response.status === 200 && response.data && response.data.data && response.data.data.length > 0) {
                return response.data.data[0].embedding;
            } else {
                console.error('获取文本向量失败:', response.data);
                throw new Error('获取文本向量失败');
            }
        } catch (error) {
            console.error('请求文本向量API异常:', error);
            throw error;
        }
    }
}

module.exports = BaiduCloud; 